﻿using Microsoft.AspNetCore.Mvc;
using YDT_UserService.Applictions.DTOs;
using YDT_UserService.Applictions.Interfaces;

namespace YDT_UserService.API.Controllers
{
    /// <summary>
    /// 用户控制器 - 处理用户相关的HTTP请求
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class UsersController : ControllerBase
    {
        private readonly IUserService _userService;

        /// <summary>
        /// 构造函数 - 依赖注入用户服务
        /// </summary>
        public UsersController(IUserService userService)
        {
            _userService = userService;
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns>用户列表</returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<UserDto>>> GetUsers()
        {
            var users = await _userService.GetAllUsersAsync();
            return Ok(users);
        }

        /// <summary>
        /// 根据ID获取用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>用户信息</returns>
        [HttpGet("{id:guid}")]
        public async Task<ActionResult<UserDto>> GetUser(Guid id)
        {
            var user = await _userService.GetUserByIdAsync(id);
            if (user == null)
            {
                return NotFound($"用户ID '{id}' 不存在");
            }
            return Ok(user);
        }

        /// <summary>
        /// 根据用户名获取用户
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns>用户信息</returns>
        [HttpGet("name/{userName}")]
        public async Task<ActionResult<UserDto>> GetUserByName(string userName)
        {
            var user = await _userService.GetUserByUserNameAsync(userName);
            if (user == null)
            {
                return NotFound($"用户名 '{userName}' 不存在");
            }
            return Ok(user);
        }

        /// <summary>
        /// 分页查询用户
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>分页用户列表</returns>
        [HttpGet("paged")]
        public async Task<ActionResult> GetPagedUsers([FromQuery] UserQueryDto query)
        {
            var (users, totalCount) = await _userService.GetPagedUsersAsync(query);
            return Ok(new { Users = users, TotalCount = totalCount });
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="createUserDto">创建用户参数</param>
        /// <returns>创建的用户信息</returns>
        [HttpPost]
        public async Task<ActionResult<UserDto>> CreateUser(CreateUserDto createUserDto)
        {
            try
            {
                var user = await _userService.CreateUserAsync(createUserDto);
                return CreatedAtAction(nameof(GetUser), new { id = user.Id }, user);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="updateUserDto">更新用户参数</param>
        /// <returns>更新后的用户信息</returns>
        [HttpPut("{id:guid}")]
        public async Task<ActionResult<UserDto>> UpdateUser(Guid id, UpdateUserDto updateUserDto)
        {
            var user = await _userService.UpdateUserAsync(id, updateUserDto);
            if (user == null)
            {
                return NotFound($"用户ID '{id}' 不存在");
            }
            return Ok(user);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id:guid}")]
        public async Task<ActionResult> DeleteUser(Guid id)
        {
            var result = await _userService.DeleteUserAsync(id);
            if (!result)
            {
                return NotFound($"用户ID '{id}' 不存在");
            }
            return NoContent();
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="changePasswordDto">修改密码参数</param>
        /// <returns>修改结果</returns>
        [HttpPatch("{id:guid}/password")]
        public async Task<ActionResult> ChangePassword(Guid id, ChangePasswordDto changePasswordDto)
        {
            try
            {
                var result = await _userService.ChangePasswordAsync(id, changePasswordDto);
                if (!result)
                {
                    return NotFound($"用户ID '{id}' 不存在");
                }
                return Ok("密码修改成功");
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginDto">登录参数</param>
        /// <returns>登录结果</returns>
        [HttpPost("login")]
        public async Task<ActionResult<UserDto>> Login(LoginDto loginDto)
        {
            try
            {
                var user = await _userService.LoginAsync(loginDto);
                if (user == null)
                {
                    return Unauthorized("用户名或密码错误");
                }
                return Ok(user);
            }
            catch (InvalidOperationException ex)
            {
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 激活用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>更新后的用户信息</returns>
        [HttpPatch("{id:guid}/activate")]
        public async Task<ActionResult<UserDto>> ActivateUser(Guid id)
        {
            var user = await _userService.ActivateUserAsync(id);
            if (user == null)
            {
                return NotFound($"用户ID '{id}' 不存在");
            }
            return Ok(user);
        }

        /// <summary>
        /// 禁用用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>更新后的用户信息</returns>
        [HttpPatch("{id:guid}/deactivate")]
        public async Task<ActionResult<UserDto>> DeactivateUser(Guid id)
        {
            var user = await _userService.DeactivateUserAsync(id);
            if (user == null)
            {
                return NotFound($"用户ID '{id}' 不存在");
            }
            return Ok(user);
        }
    }
}
